package com.demo;

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: DatetoString
 * @Description:日期格式和字符串的相互转换
 * @Author: wty
 * @Date: 2022/12/12
 */

public class DatetoString {
    @Test
    public void getStringorDate() {
        // Date → String
        Date date = new Date();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        String format = simpleDateFormat.format(date);
        System.out.println("format = " + format);

        // String → Date
        String dateStr = "2021-07-14 16:16:40.0";
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = null;
        try {
            date2 = format1.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("date2 = " + date2);
    }
}
